import React, { useState } from 'react';
import { connect } from 'umi';
import { message, Spin } from 'antd';
import InfiniteScroll from 'react-infinite-scroller';

import { TRAlert } from '#/components/index.js';
import { DownOutlined, DownloadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import type {
  IProps,
  IQueryPagePublishInfoParamsType,
  IPublishInfoDataType,
  IPublishInfoParamsType,
} from '../type';
import { ISystemHelpCenterPermissions, IOperateType } from '../type';
import { getTabMenuOptions } from '../tool';
import { SelectAll } from '../components';
import { ImportModal, FileItem, CheckboxModal } from './components';
import { fileMap } from '../dictionary';
import {
  postQueryPagePublishInfo,
  postQueryTabMenuList,
  postPublishInfo,
  getRemovePublishInfo,
  postQueryExistFile,
} from '../service';
import { havePermissions } from '../tool';
import styles from './index.less';

const SystemOperationData = (props?: IProps) => {
  const { buttonPermissions = '', currentUser } = props || {};
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isMoreLoading, setIsMoreLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [sourceData, setSourceData] = useState<IPublishInfoDataType[]>([]);
  const [threeSelectData, setThreeSelectData] = useState<any[]>([]);
  const [seletValues, setSelectValues] = useState<string[]>([]);
  const [selectOptions, setSelectOptions] = useState<any[]>([]);
  const [total, setTotal] = useState<number>(0);

  // 获取资料列表
  const getPagePublishInfoData = async (params: IQueryPagePublishInfoParamsType) => {
    setIsLoading(true);
    setIsError(false);
    const res = await postQueryPagePublishInfo(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setSourceData(res?.data?.records || []);
      setTotal(res?.data?.total ?? 0);
      setHasMore(res?.data?.total > 50 ? true : false);
    } else {
      message.error(res?.message || '系统异常');
      setIsError(true);
    }
    setIsLoading(false);
  };

  // 初始化
  const fetchData = async () => {
    setLoading(true);
    setError(false);
    const res = await postQueryTabMenuList({
      haveInfo: false,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = getTabMenuOptions(res?.data || []);
      const _params = {
        current: 1,
        size: 50,
        menuList: _data?.menuList || [],
      };
      setSelectOptions(_data?.leftNodes || []);
      setSelectValues((_data?.leftNodes || [])?.map((item: any) => item?.value));
      setThreeSelectData(_data?.modalData || []);
      setError(false);
      await getPagePublishInfoData(_params);
    } else {
      message.error(res?.message || '系统异常');
      setError(true);
    }
    setLoading(false);
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async () => {
    const result: any = await CheckboxModal.show({
      threeSelectData: threeSelectData,
      leftNodes: selectOptions,
      value: seletValues,
      title: '交易单元',
    });
    if (result.index === 1) {
      setSelectValues(result?.checkedKeys);
      const _menuList = result?.checkedNodes?.map((item: any) => item?.menu);
      const _params = {
        current: 1,
        size: 50,
        menuList: _menuList || [],
      };
      getPagePublishInfoData(_params);
      return result?.checkedKeys;
    } else {
      setSelectValues(seletValues);
      return seletValues;
    }
  };

  const onSave = async (type: IOperateType, val?: IPublishInfoDataType) => {
    const result: any = await ImportModal.show({
      record: val,
      onOk: async (params: IPublishInfoParamsType) => {
        const haveList: number[] = [];
        if (type === IOperateType.CREATE) {
          const res1: any = await postQueryExistFile(params);
          params?.fileList?.forEach((item) => {
            const obj = (res1?.data || []).find((a: number) => a === item?.fileType);
            if (obj) {
              haveList.push(obj);
            }
          });
        }
        if (haveList?.length) {
          // @ts-ignore
          const res: any = await TRAlert.show(
            `所选模块${params?.firstMenuName}${
              params?.secondMenuName ? ` / ${params?.secondMenuName}` : ''
            }${params?.tabMenuName ? ` / ${params?.tabMenuName}` : ''}已存在${
              // @ts-ignore
              haveList[0] ? fileMap[haveList[0]] : ''
              // @ts-ignore
            }${haveList[1] ? `和${fileMap[haveList[1]]}` : ''}文件，是否确认覆盖？`,
          );
          if (res.index === 1) {
            const res2: any = await postPublishInfo(params);
            if (res2 && res2.statusCode === HttpCode.SUCCESS) {
              message.success('保存成功');
            } else {
              message.error(res2?.message || '保存失败');
            }
            return res2;
          }
        } else {
          const res: any = await postPublishInfo(params);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.success('保存成功');
          } else {
            message.error(res?.message || '保存失败');
          }
          return res;
        }
      },
    });
    if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
      const _menuList = selectOptions?.map((item: any) => item?.menu);
      const _params = {
        current: 1,
        size: 50,
        menuList: _menuList || [],
      };
      await getPagePublishInfoData(_params);
    }
  };

  // 重新上传
  const onEdit = (val?: IPublishInfoDataType) => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterReSaveButton,
      buttonPermissions,
    );
    if (resoult) {
      onSave(IOperateType.UPDATE, val);
    }
  };

  const loadMore = async (page: number) => {
    if (!hasMore) return;
    setIsMoreLoading(true);
    setHasMore(total > 50 * (page + 1) ? true : false);
    const _menuList = selectOptions?.map((item: any) => item?.menu);
    const _params = {
      current: page + 1,
      menuList: _menuList || [],
      size: 50,
    };
    const res = await postQueryPagePublishInfo(_params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setTotal(res?.data?.total ?? 0);
      setSourceData([...sourceData, ...(res?.data?.records || [])]);
    } else {
      setSourceData([...sourceData]);
      message.info(res?.message || '系统异常');
    }
    setIsMoreLoading(false);
  };

  // 删除
  const onDetele = async (val?: IPublishInfoDataType) => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterRemoveButton,
      buttonPermissions,
    );
    if (resoult) {
      const obj = await TRAlert.eamDelete('是否确认删除？');
      if (obj?.index === 1) {
        const res: any = await getRemovePublishInfo({ id: val?.id });
        if (res && res.statusCode === HttpCode.SUCCESS) {
          message.success('删除成功');
          const _menuList = selectOptions?.map((item: any) => item?.menu);
          const _params = {
            current: 1,
            size: 50,
            menuList: _menuList || [],
          };
          await getPagePublishInfoData(_params);
        } else {
          message.error(res?.message || '删除失败');
        }
      }
    }
  };

  // 导入
  const handleDownloadFiles = () => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterSaveButton,
      buttonPermissions,
    );
    if (resoult) {
      onSave(IOperateType.CREATE);
    }
  };

  React.useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className={styles.container}>
      {loading ? (
        <Spin />
      ) : error ? (
        <TRDefault type={'error'} message={'系统异常'} />
      ) : (
        <div className={styles.content}>
          <div className={styles.header}>
            <SelectAll
              placeholder="请选择"
              alltitle="全部资料"
              logo={<DownOutlined />}
              showArrow={true}
              open={false}
              maxTagCount={1}
              style={{ minWidth: 389 }}
              maxTagTextLength={10}
              value={seletValues}
              onClick={handelSelectDealElement}
              options={selectOptions}
            />
            <div className={styles.button} onClick={handleDownloadFiles}>
              <DownloadOutlined className={styles.buttonLogo} />
              导入
            </div>
          </div>
          <div className={styles.center}>
            {isLoading ? (
              <Spin />
            ) : isError ? (
              <TRDefault type={'error'} message={'系统异常'} />
            ) : sourceData.length ? (
              <Spin spinning={isMoreLoading} className={styles.spinloading}>
                <div className={styles.list}>
                  <InfiniteScroll
                    initialLoad={false}
                    pageStart={0}
                    loadMore={loadMore}
                    hasMore={!loading && hasMore}
                    useWindow={false}
                    className={styles.infiniteScroll}
                  >
                    {sourceData.map((item: any) => {
                      return (
                        <div className={styles.item}>
                          <FileItem
                            data={item}
                            onEdit={onEdit}
                            onDetele={onDetele}
                            currentUser={currentUser}
                          />
                        </div>
                      );
                    })}
                  </InfiniteScroll>
                </div>
              </Spin>
            ) : (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default connect(({ systemHelpCenter, global }: { systemHelpCenter: any; global: any }) => ({
  global,
  menuCode: global?.configure?.menuCode,
  systemHelpCenter,
  currentUser: global.configure.currentUser,
  buttonPermissions: global?.configure?.buttonPermissions,
}))(SystemOperationData);
